<!--
 * @Author: bear
 * @Date: 2022-08-05 15:26:00
 * @LastEditors: bear
 * @LastEditTime: 2022-08-05 17:27:47
 * @Description: your project
 * @version: 1.0
-->
<template>
  <div class="stream">
    <br />
    <span @click="nodeCreateRead">node中fs模块createReadStream创建可读流</span>
    <br />
    <span @click="nodeCreateWrite"
      >node中fs模块createWriteStream创建可写流</span
    >
    <br />
    <span @click="nodeCreatePipe">管道流pipe</span>
    <br />
    <span @click="nodeCreateGzip">链式流pipe(压缩文件)</span>
    <br />
    <span @click="nodeCreateGunzip">链式流pipe(解压文件)</span>
  </div>
</template>
<script setup>
const fs = require("fs");
// 通过stream创建压缩包
const zlib = require("zlib");
const nodeCreateRead = () => {
  var data = "";
  // 创建可读流 路径是项目根目录
  // var readerStream = fs.createReadStream("README.md");
  var readerStream = fs.createReadStream("nodeWriteStream.txt");
  // 设置编码为 utf8
  readerStream.setEncoding("UTF8");
  // 处理流事件 data end and error
  readerStream.on("data", function (chunk) {
    data += chunk;
  });
  readerStream.on("end", function () {
    console.log(data);
  });

  readerStream.on("error", function (err) {
    console.log(err.stack);
    alert("请先创建文件");
  });
  console.log("程序执行完了");
};
const nodeCreateWrite = () => {
  // 创建可写入流（文件不用自己创建 node会自动创建nodeWriteStream.txt(自定义)文件，如果文件已经存在且文件内有内容会完全将文件里的内容覆盖掉）
  const writeDate = "我是通过node-createWriteStream写入的";
  const writeStream = fs.createWriteStream("nodeWriteStream.txt");
  // 使用utf8编码写入数据
  writeStream.write(writeDate, "UTF8");
  // 标记文件结尾
  writeStream.end();
  // 处理流事件 finish\error
  writeStream.on("finish", () => {
    console.log("写入成功");
  });
  writeStream.on("error", (err) => {
    console.log(err);
  });
  console.log("程序执行完了");
};
const nodeCreatePipe = () => {
  //   //  可读流
  //   const readerStream = fs.createReadStream("nodeWriteStream.txt");
  //   //可写流
  //   const writeStream = fs.createWriteStream("nodePipeStream.txt");
  //  可读流
  const readerStream = fs.createReadStream("font.txt");
  //可写流
  const writeStream = fs.createWriteStream("nodePipefont.txt");
  readerStream.pipe(writeStream);
};
const nodeCreateGzip = () => {
  fs.createReadStream("nodePipeStream.txt")
    .pipe(zlib.createGzip())
    .pipe(fs.createWriteStream("Gzlib.hz"));
};
const nodeCreateGunzip = () => {
  fs.createReadStream("Gzlib.hz")
    .pipe(zlib.createGunzip())
    .pipe(fs.createWriteStream("Gunzip.txt"));
};
</script>
<style scoped></style>
